package com.spring.springboot.util;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author syz
 * @date 2019/10/23
 */
@Component
public class Download {

    private static final Logger logger = LoggerFactory.getLogger(Download.class);

    public static void download(String fileUrl, String savePath) {
        try {
            // 构造URL
            URL url = new URL(fileUrl);
            // 打开连接
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            //设置请求方式，默认是GET
            urlConnection.setRequestMethod("GET");
            //设置请求超时为5s
            urlConnection.setConnectTimeout(5 * 1000);
            // 设置字符编码
            urlConnection.setRequestProperty("Charset", "UTF-8");
            // 输入流
            InputStream is = urlConnection.getInputStream();

            String fileType = fileUrl.substring(fileUrl.lastIndexOf("."));

            logger.info("文件类型:{}", fileType);

            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            File dir = new File(savePath);
            if (!dir.exists() && !dir.isDirectory()) {
                dir.mkdir();
            }
            //保存至该文件夹下
            File fileName = new File(dir, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")).concat(String.valueOf(System.currentTimeMillis())));
            OutputStream os = new FileOutputStream(fileName + fileType);

            FileUtils.copyURLToFile(url, fileName);

            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            os.close();
            is.close();

        } catch (IOException e) {
            logger.error("文件下载失败！", e);
        }
    }

}
